import { ApolloCache, InMemoryCache } from "@apollo/client/core";
import { LocalStorageWrapper, persistCache } from "apollo3-cache-persist";

import {
  createGraphQLServerErrorHandlers,
  createNetworkErrorHandlers,
} from "~/modules/api-server/error-handlers";
import { createHeadersAugmentor } from "~/modules/api-server/headers-augmentor";
import { createClient } from "~/modules/apollo/graphql-client";
import { loadAppConfig } from "~/modules/shared/app-config";
import { BootstrapContext } from "~/plugins/models";
let CONTEXT: BootstrapContext;
const setupCache = async (): Promise<ApolloCache<any>> => {
  const cache = new InMemoryCache({
    resultCaching: true,
  });
  await persistCache({
    cache,
    storage: new LocalStorageWrapper(window.localStorage),
  });
  return cache;
};

export const getContent = () => {
  return CONTEXT;
};

export const setup = async (context: BootstrapContext): Promise<void> => {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const config = loadAppConfig();

  context.data_apiServer = createClient({
    ssrMode: false,
    url: config.apiServer.url_data_serve,
    subscriptionUrl: "",
    batchEnabled: false,
    headersAugmentor: createHeadersAugmentor(),
    networkErrorHandlers: createNetworkErrorHandlers(),
    graphQLErrorHandlers: createGraphQLServerErrorHandlers(),
    connectToDevTools: true,
    cache: await setupCache(),
  }).client;

  context.explorer_apiServer = createClient({
    ssrMode: false,
    url: config.apiServer.url_explorer_serve,
    subscriptionUrl: "",
    batchEnabled: false,
    headersAugmentor: createHeadersAugmentor(),
    networkErrorHandlers: createNetworkErrorHandlers(),
    graphQLErrorHandlers: createGraphQLServerErrorHandlers(),
    connectToDevTools: true,
    cache: await setupCache(),
  }).client;

  context.dic_apiServer = createClient({
    ssrMode: false,
    url: config.apiServer.url_dic_serve,
    subscriptionUrl: "",
    batchEnabled: false,
    headersAugmentor: createHeadersAugmentor(),
    networkErrorHandlers: createNetworkErrorHandlers(),
    graphQLErrorHandlers: createGraphQLServerErrorHandlers(),
    connectToDevTools: true,
    cache: await setupCache(),
  }).client;
  context.files_apiServer = config.apiServer.url_custom_param_test;
  CONTEXT = context;
  return Promise.resolve();
};
